package com.mine.ui;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.mine.adapter.BaseQuickAdapter;
import com.mine.adapter.BaseViewHolder;
import com.mine.adapter.QuickAdapter;
import com.mine.adapter.listener.OnItemClickListener;
import com.mine.bean.PermissionBean;
import com.mine.dialog.PermissionUserDialog;
import com.mine.listener.PermissionChangeListener;
import com.mine.listener.PermissionDialogListener;
import com.mine.xpermission.PermissionCheckListener;
import com.mine.xpermission.PermissionManager;
import com.mine.xpermission.PermissionMineUtil;
import com.mine.xpermission.R;
import com.mine.xpermission.databinding.FragmentPermissionBinding;

import java.util.ArrayList;
import java.util.List;

public class PermissionFragment extends DialogFragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getDialog() != null && getDialog().getWindow() != null) {
            getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        }
        binding = FragmentPermissionBinding.inflate(inflater);
        return binding.getRoot();
    }

    FragmentPermissionBinding binding;

    private boolean isBroadRoot = false;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();
        initListener();
        setCancelable(false);
    }

    private void initListener() {
        binding.btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isComplete = PermissionManager.getInstance(getActivity()).checkAllPermissionComplete(permissionBeanList);
                logPermission("权限检查是否全部通过= " + isComplete);
                if (!isComplete) {
                    Toast.makeText(getActivity(), "软件运行需要以上权限，请通过", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (permissionChangeListener != null) {
                    permissionChangeListener.onClickComplete();
                }
            }
        });
        PermissionManager.getInstance(getActivity()).setRequestPermissionListener(new PermissionCheckListener() {
            @Override
            public void checkPermissionComplete(String action) {
                logPermission("权限请求全部通过=" + action);
                quickAdapter.notifyDataChanged();
            }

            @Override
            public void showGotoAppDetailDialog(String permission) {
                logPermission("需要显示用户详情Dialog=" + permission);
                showReNeedShowPermissionDialog(permission);
            }
        });
    }

    private void logPermission(String s) {
        Log.e("permissionLog", s);
    }

    private void showReNeedShowPermissionDialog(String permission) {
        PermissionBean permissionBean = findBeanByAction(permission);
        if (permissionBean == null) {
            Toast.makeText(getActivity(), "请求异常，请退出程序重试", Toast.LENGTH_SHORT).show();
            return;
        }
        PermissionUserDialog oridinryDialog = new PermissionUserDialog(getActivity());
        oridinryDialog.setOnDialogClickListener(new PermissionDialogListener() {
            @Override
            public void sure() {
                Intent intent = new Intent(PermissionMineUtil.getPermissDetailAction(permission));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setData(Uri.fromParts("package", getActivity().getPackageName(), null));
                startActivity(intent);
            }

            @Override
            public void noSure() {

            }
        });
        oridinryDialog.show(getString(R.string.common_permission_alert), getString(R.string.common_permission_manual_assign_fail_hint, permissionBean.getTitle()));
    }


    QuickAdapter quickAdapter;
    private List<PermissionBean> permissionBeanList = new ArrayList<>();
    private String titleShow="";

    private void initViews() {
        binding.tvPerTitle.setText(titleShow);
        binding.frameRecycle.setLayoutManager(new LinearLayoutManager(getActivity()));
        quickAdapter = new QuickAdapter<PermissionBean>(R.layout.item_permission_view) {

            @Override
            protected void convert(BaseViewHolder holder, PermissionBean item, int position, int count) {
                holder.setImageResource(R.id.iv_image_show, item.getImageId());
                holder.setText(R.id.tv_title, item.getTitle());
                holder.setText(R.id.tv_desc_content, item.getDesc());
                String action = item.getPermissionAction();
                boolean ifHasPermissoon = PermissionManager.getInstance(getActivity()).checkAppPermission(action);
                logPermission("刷新数据action=" + action + " / " + ifHasPermissoon);
                ImageView toggle_switch = holder.getView(R.id.toggle_switch);
                toggle_switch.setImageResource(ifHasPermissoon ? R.mipmap.icon_switch_open : R.mipmap.icon_switch_close);
            }
        };
        binding.frameRecycle.setAdapter(quickAdapter);
        quickAdapter.setNewData(permissionBeanList);
        quickAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter<?, ?> baseAdapter, View view, int position) {
                PermissionBean permissionBean = (PermissionBean) baseAdapter.getItem(position);
                String action = permissionBean.getPermissionAction();
                boolean isHasPermission = PermissionManager.getInstance(getActivity()).checkAppPermission(action);
                if (isHasPermission) {
                    return;
                }
                PermissionManager.getInstance(getActivity()).setBroadRoot(isBroadRoot);
                PermissionManager.getInstance(getActivity()).requestPermissionSingle(action);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (quickAdapter != null) {
            quickAdapter.notifyDataChanged();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null && dialog.getWindow() != null) {
            Window window = dialog.getWindow();
            window.setBackgroundDrawableResource(android.R.color.transparent);
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.BOTTOM;
            params.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度匹配屏幕
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setWindowAnimations(R.style.BottomDialogAnimation);
            window.setAttributes(params);
        }
    }

    public void setPermissionList(List<PermissionBean> list,String title) {
        logPermission("setPermissionList=" + list.size());
        permissionBeanList = list;
        titleShow = title;
    }

    PermissionChangeListener permissionChangeListener;

    public void setOnCallBackListener(PermissionChangeListener permissionChangeListener) {
        this.permissionChangeListener = permissionChangeListener;
    }

    private PermissionBean findBeanByAction(String permission) {
        logPermission("findBeanByAction=" + permission);
        if (permissionBeanList == null || permissionBeanList.isEmpty()) {
            return null;
        }
        PermissionBean permissionBeanBack = null;
        for (PermissionBean permissionBean : permissionBeanList) {
            String action = permissionBean.getPermissionAction();
            logPermission("findBeanByAction=forList=" + action);
            if (action.equals(permission)) {
                permissionBeanBack = permissionBean;
                break;
            }
        }
        return permissionBeanBack;
    }

    public void setBoardRoot(boolean b) {
        isBroadRoot = b;
    }

}
